﻿using HamcoWcs.DAL;
using HamcoWcs.Entitys.UserInfos;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Service.Common;
using HamcoWcs.Service.Common.SingalRs;
using Microsoft.AspNetCore.SignalR;
using Quartz;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Main.SingalRFiles
{
    /// <summary>
    /// 
    /// </summary>
    [DisallowConcurrentExecution]
    [AutoInject(typeof(IJob), InjectType.Worker)]
    public class LoginStatusWorker : IJob
    {

        private readonly IHubContext<PushHub> _monitorContext;
        private readonly WcsDbContext _wcsDbContext;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="monitorContext"></param>
        /// <param name="wcsDbContext"></param>
        public LoginStatusWorker(IHubContext<PushHub> monitorContext, WcsDbContext wcsDbContext)
        {
            _monitorContext = monitorContext;
            _wcsDbContext = wcsDbContext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public Task Execute(IJobExecutionContext context)
        {
            var states = _wcsDbContext.Set<LoginStatus>().Where(x => x.Operate != 0).ToList();

            foreach (var item in states)
            {
                if (item.IsOnline)
                {
                    _monitorContext.Clients.All.SendAsync("LoginStatus", item);
                }
                item.Operate = 0;
            }

            _wcsDbContext.SaveChanges();
            return Task.CompletedTask;
        }

    }
}
